﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Se.Framework.Web.Mvc.GenericCrud.Attributes;

namespace Se.Framework.Web.Mvc.GenericCrud
{
    public class GridBuilderFactory
    {
        public static readonly GridBuilderFactory Factory = new GridBuilderFactory();

        private readonly Dictionary<Type, IGridBuilder> builders;

        public IEnumerable<IGridBuilder> Builders
        {
            get { return builders.Values; }
        }

        private GridBuilderFactory()
        {
            builders = new Dictionary<Type, IGridBuilder>();
        }

        public void RegisterBuilder(IGridBuilder builder)
        {
            if (!builders.ContainsKey(builder.TableProperties.EntityType))
            {
                builders.Add(builder.TableProperties.EntityType, builder);
            }
            else
            {
                builders[builder.TableProperties.EntityType] = builder;
            }
        }

        public IGridBuilder FromType(Type type)
        {
            if (!builders.ContainsKey(type))
            {
                builders.Add(type, new GridBuilderDefault(new GenericCrudTableDataAttribute(type.Name, type, "Id")));
            }
            return builders[type];
        }
    }
}